package com.paad.todolist;

import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
//import android.widget.ShoppingBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class ViewShoppinglistActivity extends Activity {
	
  static final private int ADD_NEW_TODO = Menu.FIRST;
  static final private int REMOVE_TODO = Menu.FIRST + 1;
  
  private static final String TEXT_ENTRY_KEY = "TEXT_ENTRY_KEY";
  private static final String ADDING_ITEM_KEY = "ADDING_ITEM_KEY";
  private static final String SELECTED_INDEX_KEY = "SELECTED_INDEX_KEY";
  
  private boolean addingNew = false;
  private ArrayList<Squad> shoppinglistItems;
  private ListView myListView;
  private EditText myEditText;
  private SquadAdapter aa;
  private Integer shoppinglistId;
  
  ArmyDBAdapter toDoDBAdapter;
  Cursor itemCursor;
  Cursor itemIdCursor;
  
  /** Called when the activity is first created. */
  public void onCreate(Bundle peanut) {
    super.onCreate(peanut);
    setContentView(R.layout.shoppinglist);

    myListView = (ListView)findViewById(R.id.shoppingItemsListView);
    myEditText = (EditText)findViewById(R.id.shoppingItemsEditText);

    shoppinglistItems = new ArrayList<Squad>();
    int resID = R.layout.shoppinglist_item;
    aa = new SquadAdapter(this, resID, shoppinglistItems);
    myListView.setAdapter(aa);
    
    Intent activation_intent = getIntent();
    shoppinglistId = activation_intent.getExtras().getInt("id");

    myEditText.setOnKeyListener(new OnKeyListener() {
      public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN)
          if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
        	
        	  
        	/*String item_name = myEditText.getText().toString();
            Squad item = new Squad();
            item.setId((int)toDoDBAdapter.insertSquad(item.getName()));
            toDoDBAdapter.insertListing(item.getId(), shoppinglistId);
            updateArray();
            myEditText.setText("");
            aa.notifyDataSetChanged();
            cancelAdd();*/
            return true;
          }
        return false;
      }
    });
        
    myListView.setOnItemClickListener(new OnItemClickListener() {
    	public void onItemClick(AdapterView<?> av, View v, int position, long id) {
    	  Squad item = shoppinglistItems.get(position);
    	  /*Boolean is_done = !item.getDone();
    	  item.setDone(is_done);
    	  CheckBox box = (CheckBox) v.findViewById(R.id.is_done);
    	  box.setChecked(is_done);*/
    	}
    });

    registerForContextMenu(myListView);
    restoreUIState();

    toDoDBAdapter = new ArmyDBAdapter(this);

    // Open or create the database
    toDoDBAdapter.open();

    populateItemList();
  }
  
  private void populateItemList() {
    // Get all the todo list items from the database.
    itemIdCursor = toDoDBAdapter.getArmyCursor(shoppinglistId);
    startManagingCursor(itemIdCursor);
      
    // Update the array.
    updateArray();
  }

  private void updateArray() {
	  itemIdCursor.requery();

	  shoppinglistItems.clear();
	    
	  if (itemIdCursor.moveToFirst())
	    do {
	    	int item_id = itemIdCursor.getInt(itemIdCursor.getColumnIndex(ArmyDBAdapter.KEY_LISTING_SQUAD_ID));
	    	itemCursor = toDoDBAdapter.getSquadCursor(item_id);
	    	if(itemCursor.moveToFirst())
	    	{
		      String name = itemCursor.getString(itemCursor.getColumnIndex(ArmyDBAdapter.KEY_SQUAD_TYPE));
		      //Boolean is_done = itemsCursor.getInt(itemsCursor.getColumnIndex(ShoppinglistsDBAdapter.KEY_ITEM_DONE)) > 0;
		      int id = itemCursor.getInt(itemCursor.getColumnIndex(ArmyDBAdapter.KEY_ID));
		      Squad newItem = new Squad(name);
		      newItem.setId(id);
		      newItem.setName(name);
		      shoppinglistItems.add(shoppinglistItems.size(), newItem);
		      itemCursor.close();
	    	}
	    } while(itemIdCursor.moveToNext());
	  
	  aa.notifyDataSetChanged();
	}

  private void restoreUIState() {
    // Get the activity preferences object.
    SharedPreferences settings = getPreferences(0);

    // Read the UI state values, specifying default values.
    String text = settings.getString(TEXT_ENTRY_KEY, "");
    Boolean adding = settings.getBoolean(ADDING_ITEM_KEY, false);

    // Restore the UI to the previous state.
    if (adding) {
      addNewItem();
      myEditText.setText(text);
    }
  }
  
  @Override
  public void onSaveInstanceState(Bundle outState) {
    outState.putInt(SELECTED_INDEX_KEY, myListView.getSelectedItemPosition());

    super.onSaveInstanceState(outState);
  }

  @Override
  public void onRestoreInstanceState(Bundle savedInstanceState) {
    int pos = -1;

    if (savedInstanceState != null)
      if (savedInstanceState.containsKey(SELECTED_INDEX_KEY))
        pos = savedInstanceState.getInt(SELECTED_INDEX_KEY, -1);

    myListView.setSelection(pos);
  }
  
  protected Dialog onCreateDialog(int id) {
      Dialog dialog = null;
      switch(id) {
      case 1:
    	  final CharSequence[] items = {"5 Swordsman '1'", "12 Swordsman '2'", "3 Archers '1'", "7 Archers '2'", "5 Cavalry '2'"};

    	  AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	  builder.setTitle("Pick a Squad");
    	  builder.setItems(items, new DialogInterface.OnClickListener() {
    	      public void onClick(DialogInterface dialog, int item) {
    	    	  if(item == 0){
    	    		  String item_name = "swordsmanA";
    	    		  Squad item1 = new Squad(item_name);
    	    		  item1.setId((int)toDoDBAdapter.insertSquad(item1.squadType));
    	    		  toDoDBAdapter.insertListing(item1.getId(), shoppinglistId);
    	    		  updateArray();
    	    		  aa.notifyDataSetChanged();
    	    		  cancelAdd();
    	    		  Toast.makeText(getApplicationContext(), "Added Swordsman Squad", Toast.LENGTH_LONG).show();
    	    	  }else if(item == 1){
    	    		  String item_name = "swordsmanB";
    	    		  Squad item1 = new Squad(item_name);
    	    		  item1.setId((int)toDoDBAdapter.insertSquad(item1.squadType));
    	    		  toDoDBAdapter.insertListing(item1.getId(), shoppinglistId);
    	    		  updateArray();
    	    		  aa.notifyDataSetChanged();
    	    		  cancelAdd();
    	    		  Toast.makeText(getApplicationContext(), "Added large Swordsman Squad", Toast.LENGTH_LONG).show();
    	    	  }else if(item == 2){
    	    		  String item_name = "archerA";
    	    		  Squad item1 = new Squad(item_name);
    	    		  item1.setId((int)toDoDBAdapter.insertSquad(item1.squadType));
    	    		  toDoDBAdapter.insertListing(item1.getId(), shoppinglistId);
    	    		  updateArray();
    	    		  aa.notifyDataSetChanged();
    	    		  cancelAdd();
    	    		  Toast.makeText(getApplicationContext(), "Added Archer Squad", Toast.LENGTH_LONG).show();
    	    	  }else if(item == 3){
    	    		  String item_name = "archerB";
    	    		  Squad item1 = new Squad(item_name);
    	    		  item1.setId((int)toDoDBAdapter.insertSquad(item1.squadType));
    	    		  toDoDBAdapter.insertListing(item1.getId(), shoppinglistId);
    	    		  updateArray();
    	    		  aa.notifyDataSetChanged();
    	    		  cancelAdd();
    	    		  Toast.makeText(getApplicationContext(), "Added large Archer Squad", Toast.LENGTH_LONG).show();
    	    	  }else if(item == 4){
    	    		  String item_name = "cavalry";
    	    		  Squad item1 = new Squad(item_name);
    	    		  item1.setId((int)toDoDBAdapter.insertSquad(item1.squadType));
    	    		  toDoDBAdapter.insertListing(item1.getId(), shoppinglistId);
    	    		  updateArray();
    	    		  aa.notifyDataSetChanged();
    	    		  cancelAdd();
    	    		  Toast.makeText(getApplicationContext(), "Added Elite Cavalry Squad", Toast.LENGTH_LONG).show();
    	    	  }
    	      }
    	  });
    	  AlertDialog alert = builder.create();
    	  dialog = alert;
          break;
          
      default:
          dialog = null;
      }
      return dialog;
}
  
  @Override
  protected void onPause() {
    super.onPause();
    
    // Get the activity preferences object.
    SharedPreferences uiState = getPreferences(0);
    // Get the preferences editor.
    SharedPreferences.Editor editor = uiState.edit();

    // Add the UI state preference values.
    editor.putString(TEXT_ENTRY_KEY, myEditText.getText().toString());
    editor.putBoolean(ADDING_ITEM_KEY, addingNew);
    // Commit the preferences.
    editor.commit();

    // Closes the DB connection.
    toDoDBAdapter.close();
  }
  
  @Override
  public void onResume() {
	super.onResume();
	  	
	// Reopens the DB connection.
	toDoDBAdapter.open();
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    // Create and add new menu items.
    MenuItem itemAdd = menu.add(0, ADD_NEW_TODO, Menu.NONE,
                                R.string.add_new);
    MenuItem itemRem = menu.add(0, REMOVE_TODO, Menu.NONE,
                                R.string.remove);

    // Assign icons
    itemAdd.setIcon(R.drawable.add_new_item);
    itemRem.setIcon(R.drawable.remove_item);

    // Allocate shortcuts to each of them.
    itemAdd.setShortcut('0', 'a');
    itemRem.setShortcut('1', 'r');

    return true;
  }

  @Override
  public boolean onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);

    int idx = myListView.getSelectedItemPosition();

    String removeTitle = getString(addingNew ? 
                                   R.string.cancel : R.string.remove);

    MenuItem removeItem = menu.findItem(REMOVE_TODO);
    removeItem.setTitle(removeTitle);
    removeItem.setVisible(addingNew || idx > -1);

    return true;
  }
  
  @Override
  public void onCreateContextMenu(ContextMenu menu, 
                                  View v, 
                                  ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    menu.setHeaderTitle("Selected Squad");
    menu.add(0, REMOVE_TODO, Menu.NONE, R.string.remove);
  }
  
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);

    int index = myListView.getSelectedItemPosition();

    switch (item.getItemId()) {
      case (REMOVE_TODO): {
        if (addingNew) {
          cancelAdd();
        } 
        else {
          removeItem(index);
        }
        return true;
      }
      case (ADD_NEW_TODO): { 
        addNewItem();
        return true; 
      }
    }

    return false;
  }
  
  @Override
  public boolean onContextItemSelected(MenuItem item) {  
    super.onContextItemSelected(item);
    switch (item.getItemId()) {
      case (REMOVE_TODO): {
        AdapterView.AdapterContextMenuInfo menuInfo;
        menuInfo =(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        int index = menuInfo.position;
        int theId = (shoppinglistItems.get(index)).getId();

        removeItem(theId);
        return true;
      }
    }
    return false;
  }
  
  @Override
  public void onDestroy() {
    super.onDestroy();
      
    // Close the database
    toDoDBAdapter.close();
  }
  
  private void cancelAdd() {
    addingNew = false;
    myEditText.setVisibility(View.GONE);
  }

  private void addNewItem() {
    addingNew = true;
    showDialog(1);
    /*
    myEditText.setVisibility(View.VISIBLE);
    myEditText.requestFocus(); 
    */
  }

  private void removeItem(int _index) {
    // Items are added to the listview in reverse order, so invert the index.
    toDoDBAdapter.removeSquad(_index);
    updateArray();
  }
}